<template>
  <div class="correction-test">
    <AppHeader
      :title="headerTitle"
      :showRight="true"
      :banAnimate="true"
      @rightClickEvent="questionPopupShow = true"
      @leftClickEvent="handleHeaderLeft()"
    >
      <template #right>
        <img
          src="@/assets/images/wrongBook/icon-select-question.png"
          width="20"
          height="20"
        />
      </template>
    </AppHeader>
    <question-base-page
      v-if="isShowBasePage && !isSubmit"
      :bigQuestionDetail="curBigQuestion"
      :smallQuestionDetail="curSmallQuestion"
      :isBigAudioFlag="questionTypeConfig.isBigAudioFlag"
      style="height: calc(100vh - 44px)"
      @getNextQuestion="getNextQuestion()"
    />
    <!-- 提交作业 -->
    <question-submit v-if="isSubmit" :bigQuestionList123="bigQuestionList" style="height: calc(100vh - 44px)" />
  </div>

  <question-list-popup
    v-model:show="questionPopupShow"
    :list="bigQuestionList"
    @closed="questionPopupShow = false"
    @handleItem="handleQuestionItem"
  />

  <!-- 是否显示要看接口返回/本地存储!!!!!! -->
  <div
    v-if="darkStepShow"
    class="correction-dark-step"
    :style="firstStep ? '' : 'padding-top: 44px'"
  >
    <template v-if="firstStep" class="first-step">
      <div v-html="curBigQuestion.title" class="test-info"></div>
      <div class="guide">
        <span class="explain1">
          <span>你可以在“我 > 学习设置”里面</span>
          <span>关闭题型模板的音频</span>
        </span>
        <img
          src="@/assets/images/wrongBook/icon-guide1.png"
          class="icon-guide1"
        />
      </div>
      <div class="btn">
        <div @click="goToSetQuestionTypeConfig()">去设置</div>
        <div @click="firstStep = false">暂不设置</div>
      </div>
    </template>
    <template v-else class="second-step">
      <div class="icon-guide2">
        <img src="@/assets/images/wrongBook/icon-guide2.png" />
      </div>
      <div class="explain2"><span>点击可选题目进行作答</span></div>
      <div class="btn">
        <div @click="handleOk()">OK，我知道了</div>
      </div>
    </template>
  </div>

  <AppLoading v-if="loading.page" />
</template>
<script setup>
import { onMounted, reactive, toRefs, computed } from "vue";
import { useRouter, useRoute } from "vue-router";
import { request } from "@/api/request.js";
import wrongApi from "@/api/wrong.js";

import AppHeader from "@/components/AppHeader.vue";
import AppLoading from "@/components/AppLoading.vue";
import QuestionBasePage from "./components/QuestionBasePage.vue";
import QuestionListPopup from "./components/QuestionListPopup.vue";
import QuestionSubmit from "./components/QuestionSubmit.vue";
import { showToast } from "vant";

const route = useRoute();
const router = useRouter();
const { title: subTitle, id: testId } = route.query;

const state = reactive({
  loading: {
    page: false,
  },
  questionTypeConfig: {},
  isShowBasePage: false, // 控制题目展示
  darkStepShow: false, // 从接口获取/本地存储 (确定是否一天过期,还是点过就不再弹出)!!!!
  firstStep: true, // 第一步
  questionPopupShow: false,
  bigQuestionList: [],
  smallQuestionList: [],
  curBigQuestionIndex: 0,
  curSmallQuestionIndex: 0,
  isSubmit: false,
});

const headerTitle = computed(() => {
  return `订正错题 ${subTitle}`;
});
const curBigQuestion = computed(() => {
  // 当前大题
  return state.bigQuestionList[state.curBigQuestionIndex];
});
const curSmallQuestion = computed(() => {
  //当前小题
  return state.smallQuestionList[state.curSmallQuestionIndex];
});
onMounted(() => {
  state.loading.page = true;
  state.darkStepShow =
    localStorage.getItem("wrongBook-correction-darkStepShow") === "false";
  Promise.all([
    getRecordDetail(),
    getBigQuestionList(),
    getQuestionTypeConfig(),
  ])
    .then(async (list) => {
      const recordDetail = list[0]; // 记录的是大题
      state.bigQuestionList = list[1];
      if (recordDetail && state.bigQuestionList.length) {
        state.curBigQuestionIndex = state.bigQuestionList.findIndex(
          (item) => item.id === recordDetail.id
        );
        state.curBigQuestionIndex =
          state.curBigQuestionIndex < 0 ? 0 : state.curBigQuestionIndex;
      }
      if (state.bigQuestionList.length) {
        state.smallQuestionList = await getSamllQuestionList(
          state.bigQuestionList[state.curBigQuestionIndex]
        ); // 注意:要先获取试题记录!!!!!
      }
      state.questionTypeConfig = list[2];
      state.isShowBasePage = true;
    })
    .finally(() => {
      state.loading.page = false;
    });
});
// 获取题型模板音频配置
const getQuestionTypeConfig = () => {
  return new Promise((resolve) => {
    request(wrongApi.getQuestionTypeConfig)
      .then((res) => {
        const { data } = res || {};
        if (data && +data.code === 1 && data.data) {
          resolve(data.data);
        } else {
          throw res;
        }
      })
      .catch((e) => {
        resolve({
          isBigAudioFlag: false,
        });
      });
  });
};
// 获取学习记录
const getRecordDetail = () => {
  return new Promise((resolve) => {
    request(wrongApi.getRecordDetail, {
      data: { id: testId, month: 1 }, // 参数有待确认!!!!
    })
      .then((res) => {
        const { data } = res || {};
        if (data && +data.code === 1 && data.data) {
          resolve(data.data);
        } else {
          throw res;
        }
      })
      .catch((e) => {
        resolve({
          id: 2,
          desc: "第二大题",
          title: `<div>
              二、信息获取第二节 听选信息听三段对话，每段播放两遍。各段播放前你有10秒钟的阅题时间。各段播放后有两个问题。请根据所听到的问题和括号内的提示，在8秒钟内选择正确的信息口头回
              答问题。
              听第一段对话，回答两个问题。现在你有10秒钟的阅题时间。
            </div>`,
        });
      });
  });
};
// 获取试卷大题列表
const getBigQuestionList = () => {
  return new Promise((resolve, reject) => {
    request(wrongApi.getBigQuestionList, {
      data: { id: testId },
    })
      .then((res) => {
        const { data } = res || {};
        if (data && +data.code === 1 && data.data) {
          // resolve(data.data)
          resolve([]);
        } else {
          throw res;
        }
      })
      .catch((e) => {
        resolve([
          {
            id: 1,
            desc: "第一大题",
            title: `<div>
              一、信息获取第一节 听选信息听三段对话，每段播放两遍。各段播放前你有10秒钟的阅题时间。各段播放后有两个问题。请根据所听到的问题和括号内的提示，在8秒钟内选择正确的信息口头回
              答问题。
              听第一段对话，回答两个问题。现在你有10秒钟的阅题时间。
            </div>`,
            audioSrc:
              "https://webfs.hw.kugou.com/202405292222/9915719e351c70d818446e7209d69a5d/KGTX/CLTX003/c2911fa8907df4b892e7236f8277ef91.mp3",
          },
          {
            id: 2,
            desc: "第二大题",
            title: `<div>
              二、信息获取第二节 听选信息听三段对话，每段播放两遍。各段播放前你有10秒钟的阅题时间。各段播放后有两个问题。请根据所听到的问题和括号内的提示，在8秒钟内选择正确的信息口头回
              答问题。
              听第一段对话，回答两个问题。现在你有10秒钟的阅题时间。
            </div>`,
            audioSrc:
              "https://webfs.hw.kugou.com/202405292222/9915719e351c70d818446e7209d69a5d/KGTX/CLTX003/c2911fa8907df4b892e7236f8277ef91.mp3",
          },
          {
            id: 3,
            desc: "第三大题",
            title: `<div>
              三、信息获取第二节 听选信息听三段对话，每段播放两遍。各段播放前你有10秒钟的阅题时间。各段播放后有两个问题。请根据所听到的问题和括号内的提示，在8秒钟内选择正确的信息口头回
              答问题。
              听第一段对话，回答两个问题。现在你有10秒钟的阅题时间。
            </div>`,
            audioSrc:
              "https://webfs.hw.kugou.com/202405292222/9915719e351c70d818446e7209d69a5d/KGTX/CLTX003/c2911fa8907df4b892e7236f8277ef91.mp3",
          },
        ]);
        // showToast(e.msg || (e.body && e.body.msg) || "获取题目失败");
      });
  });
};
// 获取小题列表
const getSamllQuestionList = ({ id }) => {
  return new Promise((resolve) => {
    request(wrongApi.getSmallQuestionList, {
      data: { id: testId },
    })
      .then((res) => {
        const { data } = res || {};
        if (data && +data.code === 1 && data.data) {
          resolve(data.data);
        } else {
          throw res;
        }
      })
      .catch((e) => {
        resolve([
          {
            id: 1,
            content: `<div>
              1. What is David doing on hiscomputer?(doing his homework / watching amatch /listening to music)
            </div>`,
            audioSrc:
              "https://webfs.hw.kugou.com/202405292222/9915719e351c70d818446e7209d69a5d/KGTX/CLTX003/c2911fa8907df4b892e7236f8277ef91.mp3",
          },
          {
            id: 2,
            title: "第二大题",
            content: `<div>
              2. How long can Sandy use hercomputerevery day?
              (for one hour / for half an hour /for twohours)。
            </div>`,
            audioSrc:
              "https://webfs.hw.kugou.com/202405292222/9915719e351c70d818446e7209d69a5d/KGTX/CLTX003/c2911fa8907df4b892e7236f8277ef91.mp3",
          },
        ]);
      });
  });
};
// 去学习设置,关闭题型模板音频
const goToSetQuestionTypeConfig = () => {
  router.replace({
    path: "",
  });
};

const handleHeaderLeft = () => {
  router.go(-1);
};
const handleOk = () => {
  state.darkStepShow = false;
  localStorage.setItem("wrongBook-correction-darkStepShow", "false");
};
// 选做大题
const handleQuestionItem = (data) => {
  state.curBigQuestionIndex = state.bigQuestionList.find(
    (item) => item.id === data.id
  );
  state.questionPopupShow = false;
};
const getNextQuestion = () => {
  // 判断有没有跳题目!!!!
  const { curSmallQuestionIndex, smallQuestionList, curBigQuestionIndex } =
    state;
  if (
    curBigQuestionIndex + 1 >= bigQuestionList.length &&
    curSmallQuestionIndex + 1 >= smallQuestionList.length
  ) {
    // 该提交了
    state.isSubmit = true;
    return;
  }
  if (curSmallQuestionIndex + 1 >= smallQuestionList.length) {
    // 下一大题
    state.curBigQuestionIndex += 1;
    state.curSmallQuestionIndex = 0;
  } else {
    state.curSmallQuestionIndex += 1;
  }
};

const {
  loading,
  bigQuestionList,
  questionTypeConfig,
  darkStepShow,
  firstStep,
  questionPopupShow,
  isShowBasePage,
  isSubmit,
} = toRefs(state);
</script>
<style scoped lang="scss">
.correction-test {
  font-family: PingFangSC, PingFang SC;
  background: #f5f5f5;
  height: 100%;
  padding-top: 44px;
  box-sizing: border-box;
}
.correction-dark-step {
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  padding: 54px 10px 0;
  box-sizing: border-box;
  position: fixed;
  top: 0;
  bottom: 0;
  z-index: 500;
  display: flex;
  flex-direction: column;
  .test-info {
    background: #ffffff;
    border-radius: 15px;
    padding: 10px 10px 15px;
    width: 100%;
    box-sizing: border-box;
  }
  .guide {
    padding-top: 16px;
    position: relative;
    .icon-guide1 {
      width: 158px;
      float: right;
    }
    .explain1 {
      font-size: 14px;
      color: #fff;
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: flex-end;
      position: absolute;
      bottom: 10%;
      left: 50%;
      transform: translate(-50%, 0);
      span {
        white-space: nowrap;
        line-height: 25px;
      }
    }
  }
  .btn {
    font-size: 12px;
    display: flex;
    justify-content: space-around;
    div {
      color: #fff;
      width: 100px;
      height: 32px;
      border: 1px solid #fff;
      border-radius: 16px;
      display: flex;
      justify-content: center;
      align-items: center;
    }
  }

  .icon-guide2 {
    display: flex;
    justify-content: flex-end;
    img {
      width: 157px;
    }
  }
  .explain2 {
    font-size: 14px;
    color: #fff;
    text-align: center;
    padding: 14px 0 20px;
  }
}
</style>
